import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
import 'package:web_socket_channel/status.dart' as status;

class WebSocketModel extends ChangeNotifier {
  WebSocketChannel? _channel;
  bool _connected = false;
  List<Map<String, dynamic>> _messages = [];
  String? _errorMessage;
  
  // 连接状态
  bool get connected => _connected;
  
  // 消息列表
  List<Map<String, dynamic>> get messages => _messages;
  
  // 错误信息
  String? get errorMessage => _errorMessage;
  
  // 连接到WebSocket服务器
  void connect(String url, {Map<String, dynamic>? headers}) {
    try {
      // 如果已经连接，先断开
      if (_connected) {
        disconnect();
      }
      
      // 建立连接
      _channel = WebSocketChannel.connect(
        Uri.parse(url),
      );

      _channel!.sink.add(jsonEncode({
        'userId': headers?['id'],
        'accessToken': headers?['accessToken'],
      }));

      _connected = true;
      _errorMessage = null;
      notifyListeners();
      
      // 监听消息
      _channel!.stream.listen(
        (message) {
          try {
            // 尝试解析JSON消息
            final data = jsonDecode(message);
            _messages.add({
              'timestamp': DateTime.now(),
              'data': data,
              'type': 'received',
            });
          } catch (e) {
            // 如果不是JSON，作为纯文本处理
            _messages.add({
              'timestamp': DateTime.now(),
              'data': message,
              'type': 'received',
            });
          }
          
          // 保持最新的100条消息
          if (_messages.length > 100) {
            _messages.removeAt(0);
          }
          
          notifyListeners();
        },
        onError: (error) {
          _connected = false;
          _errorMessage = 'WebSocket错误: $error';
          notifyListeners();
          if (kDebugMode) {
            print('WebSocket error: $error');
          }
        },
        onDone: () {
          _connected = false;
          notifyListeners();
          if (kDebugMode) {
            print('WebSocket connection closed');
          }
        },
      );
    } catch (e) {
      _connected = false;
      _errorMessage = '连接失败: $e';
      notifyListeners();
      if (kDebugMode) {
        print('Failed to connect: $e');
      }
    }
  }
  
  // 发送文本消息
  void sendMessage(String message) {
    if (_connected && _channel != null) {
      _channel!.sink.add(message);
      // 保存发送的消息
      _messages.add({
        'timestamp': DateTime.now(),
        'data': message,
        'type': 'sent',
      });
      
      // 保持最新的100条消息
      if (_messages.length > 100) {
        _messages.removeAt(0);
      }
      
      notifyListeners();
    } else {
      _errorMessage = '未连接到服务器';
      notifyListeners();
    }
  }
  
  // 发送JSON数据
  void sendJson(Map<String, dynamic> data) {
    if (_connected && _channel != null) {
      final jsonString = jsonEncode(data);
      _channel!.sink.add(jsonString);
      // 保存发送的消息
      _messages.add({
        'timestamp': DateTime.now(),
        'data': data,
        'type': 'sent',
      });
      
      // 保持最新的100条消息
      if (_messages.length > 100) {
        _messages.removeAt(0);
      }
      
      notifyListeners();
    } else {
      _errorMessage = '未连接到服务器';
      notifyListeners();
    }
  }
  
  // 断开连接
  void disconnect() {
    if (_channel != null) {
      _channel!.sink.close(status.goingAway);
      _channel = null;
    }
    _connected = false;
    notifyListeners();
  }
  
  // 清除消息历史
  void clearMessages() {
    _messages.clear();
    notifyListeners();
  }
  
  // 重置错误信息
  void clearError() {
    _errorMessage = null;
    notifyListeners();
  }
}
